<template>
  <div>
    <el-form label-width="120px">
      <el-form-item label="SPU名称">
        <div>{{ spuName }}</div>
      </el-form-item>
      <el-form-item label="SKU名称">
        <el-input
          type="text"
          placeholder="请输入SKU名称"
          v-model="skuParams.skuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input type="number" v-model="skuParams.price"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input type="number" v-model="skuParams.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
          type="textarea"
          placeholder="请输入SKU描述"
          v-model="skuParams.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form inline>
          <el-form-item
            :label="attr.attrName"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <el-select placeholder="请选择" v-model="attr.attrParams">
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="(attrValue, index) in attr.attrValueList"
                :key="attrValue.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form inline>
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="(saleAttr, index) in saleAttrList"
            :key="saleAttr.id"
          >
            <el-select placeholder="请选择" v-model="saleAttr.saleAttrParams">
              <el-option
                :label="saleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttrValue.id}`"
                v-for="(saleAttrValue, index) in saleAttr.spuSaleAttrValueList"
                :id="saleAttrValue.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table border :data="imageList" ref="tableRef">
          <el-table-column type="selection" width="60px" />
          <el-table-column label="图片">
            <template #="{ row, $index }">
              <img
                :src="row.imgUrl"
                alt=""
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" />
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                v-if="!row.isChecked"
                type="primary"
                size="small"
                @click="setDefault(row)"
                >设置为默认</el-button
              >
              <el-button v-else type="warning" plain size="small"
                >默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSku">保存</el-button>
        <el-button @click="cancelHandler">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref } from "vue";
import { ElMessage } from "element-plus";

import {
  reqAttrList,
  reqSpuSaleAttrList,
  reqSpuImageList,
  reqAddSku,
} from "@/api/product/Spu"; // 请求函数
import type {
  IAttrList,
  ISpuSaleAttrList,
  IImageList,
  IAddSkuParams,
  IImage,
  ISkuParams,
} from "@/api/product/Spu/model"; // 数据类型

const emit = defineEmits(["changeScene"]);
const attrList = ref<IAttrList>([]); // 平台属性数据
const saleAttrList = ref<ISpuSaleAttrList>([]); // 销售属性数据
const imageList = ref<IImageList>([]); // 图片数据
const tableRef = ref(); // table组件的实例
const spuName = ref<string>(""); // spu名称
const skuParams = ref<IAddSkuParams>({
  category3Id: "",
  price: 0,
  skuAttrValueList: [],
  skuDefaultImg: "",
  skuDesc: "",
  skuName: "",
  skuSaleAttrValueList: [],
  spuId: undefined,
  tmId: "",
  weight: "",
});

// 获取添加sku所需的数据
const getAddSkuData = async ({ spu, category1Id, category2Id }: ISkuParams) => {
  spuName.value = spu.spuName;
  const attrListData = reqAttrList(category1Id, category2Id, spu.category3Id);
  const spuSaleAttrListData = reqSpuSaleAttrList(spu.id);
  const spuImageList = reqSpuImageList(spu.id);

  const result = await Promise.all([
    attrListData,
    spuSaleAttrListData,
    spuImageList,
  ]);

  attrList.value = result[0];
  saleAttrList.value = result[1];
  imageList.value = result[2];

  imageList.value.forEach((item, index) => {
    if (index == 0) {
      item.isChecked = 1;
      nextTick(() => {
        tableRef.value.toggleRowSelection(item, true);
        skuParams.value.skuDefaultImg = item.imgUrl;
      });
    } else {
      item.isChecked = 0;
    }
  });
};

// 将图片设置为默认图片
const setDefault = (row: IImage) => {
  imageList.value.forEach((item) => {
    item.isChecked = 0;
    tableRef.value.toggleRowSelection(item, false);
  });

  row.isChecked = 1;
  tableRef.value.toggleRowSelection(row, true);
  skuParams.value.skuDefaultImg = row.imgUrl;
};

// 保存按钮的回调
const saveSku = async () => {
  skuParams.value.skuAttrValueList = attrList.value.reduce((prev, next) => {
    if (next.attrParams) {
      const [attrId, valueId]: any = next.attrParams.split(":");
      prev.push({ attrId, valueId });
    }
    return prev;
  }, [] as any);
  skuParams.value.skuSaleAttrValueList = saleAttrList.value.reduce(
    (prev, next) => {
      if (next.saleAttrParams) {
        const [saleAttrId, saleAttrValueId]: any =
          next.saleAttrParams.split(":");
        prev.push({ saleAttrId, saleAttrValueId });
      }
      return prev;
    },
    [] as any
  );

  try {
    await reqAddSku(skuParams.value);
    ElMessage({
      type: "success",
      message: "添加成功",
    });
    emit("changeScene", { cutScene: 0, flag: 1 });
  } catch (error) {
    ElMessage({
      type: "error",
      message: "添加失败",
    });
  }
};

// 取消按钮的回调
const cancelHandler = () => {
  emit("changeScene", { cutScene: 0, flag: 1 });
  removeAddSkuData();
};

// 删除添加sku所需的数据
const removeAddSkuData = () => {
  saleAttrList.value = [];
  imageList.value = [];
  attrList.value = [];
  skuParams.value = {
    category3Id: "",
    price: 0,
    skuAttrValueList: [],
    skuDefaultImg: "",
    skuDesc: "",
    skuName: "",
    skuSaleAttrValueList: [],
    spuId: undefined,
    tmId: "",
    weight: "",
  };
};

// 对外暴露方法
defineExpose({
  getAddSkuData,
  removeAddSkuData,
});
</script>
